package com.ifgostudio.framework.util;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

/**
 * <b>Description</b>:根据具体图片判断真实的文件类型,不是通过扩展名判断<br/>
 * <b>Author</b>: linxuexin<br/>
 * <b>Link</b>: Email:<a href="mailto:linxuexin0423@gmail.com">linxuexin0423@gmail.com</a>;Telephone:13799286849;QQ:30268646;林先生<br/>
 * <b>Copyright</b>: <a href="http://www.ifgostudio.com" target="_blank">www.ifgostudio.com</a> all rights reserved<br/>
 * <b>Information</b>: 对外承接网站制作,价格优惠,服务一流,强有力的技术支持,asp,Jsp,Hibernate,Struts2,MS SQLServer,Oracle,jQuery,Css+div布局,Dhtml<br/>
 * <b>Create Date</b>: Aug 26, 2008 9:50:15 AM<br/>
 * <b>Version</b>: Since JDK 1.5.0<br/>
 * <b>Package</b>: com.ifgostudio.framework.util
 */
public class PictureFormat
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		File f = new File("c://test.bmp");
        if (f.exists()) {
            System.out.println(getFormatInFile(f));
        }

	}
	 // Returns the format of the image in the file 'f'.
	// Returns null if the format is not known.
	public static String getFormatInFile(File f)
	{
		return getFormatName(f);
	}

	// Returns the format name of the image in the object 'o'.
	// Returns null if the format is not known.
	private static String getFormatName(Object o)
	{
		try
		{
			// Create an image input stream on the image
			ImageInputStream iis = ImageIO.createImageInputStream(o);

			// Find all image readers that recognize the image format
			Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
			if(!iter.hasNext())
			{
				// No readers found
				return null;
			}

			// Use the first reader
			ImageReader reader = iter.next();

			// Close stream
			iis.close();

			// Return the format name
			return reader.getFormatName();
		}
		catch(IOException e)
		{
			//
		}

		// The image could not be read
		return null;
	}

}
